package application.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import application.models.Modwinetypes;
import application.models.Modwinewineries;
import application.models.Modwinewines;

import library.Controller;

/**
 * Servlet implementation class wine
 */
public class wine extends Controller {
	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("unchecked")	
	public void list(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		String name = this.getClass().getSimpleName();
		if(request.getSession().getAttribute("user")!= null) {
			SessionFactory sessionFactory = new Configuration()
			.configure()
			.buildSessionFactory();
		//Start session
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		
		List<Modwinewines> wines = (List<Modwinewines>) session.createQuery("from Modwinewines").list();
		request.setAttribute("wines", wines);
		
		out.flush();
		include(request,response,"/layout/"+name+"/list.jsp");
		
		session.getTransaction().commit();
		session.close();
		} else {
			response.sendRedirect("administrator?op=login");
		}
	}
	
	@SuppressWarnings("unchecked")
	public void edit(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		String name = this.getClass().getSimpleName();
		
		if(request.getParameter("id") == null)
			response.sendRedirect(name+"?op=list");
		
		int idWhine = Integer.parseInt((String) request.getParameter("id"));
		
		if(request.getSession().getAttribute("user")!= null) {
			//Prepare Session
			SessionFactory sessionFactory = new Configuration()
				.configure()
				.buildSessionFactory();
			//Start session
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			
			Query sql = session.createQuery("from Modwinewines where wine_id =:id");
			List<Modwinewines> wines = (List<Modwinewines>) sql.setInteger("id", idWhine).list();
			
			if(wines.isEmpty())
				response.sendRedirect(name+"?op=list");
			else {
				out.flush();
				request.setAttribute("wine", (Modwinewines) wines.get(0));
				include(request,response,"/layout/"+name+"/edit.jsp");
			}
			
			session.getTransaction().commit();
			session.close();			
		}else {
			response.sendRedirect("administrator?op=login");
		}
	}
	
	public void add(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		String name = this.getClass().getSimpleName();
		if(request.getSession().getAttribute("user")!= null) {
			out.flush();
			request.setAttribute("wine", null);
			include(request,response,"/layout/"+name+"/edit.jsp");
		}else {
			response.sendRedirect("administrator?op=login");
		}
	}
	
	@SuppressWarnings({ "unchecked" })
	public void save(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		try {
			String name = this.getClass().getSimpleName();
			if(request.getSession().getAttribute("user")!= null) {
				//Prepare Session
				SessionFactory sessionFactory = new Configuration()
					.configure()
					.buildSessionFactory();
				//Start session
				Session session = sessionFactory.openSession();
				session.beginTransaction();	
				
				if(request.getParameter("id")!= null){
					int wine_id = Integer.parseInt((String) request.getParameter("id"));
					Query sql = session.createQuery("from Modwinewines where wine_id =:id");
					
					List<Modwinewines> wines = (List<Modwinewines>) sql.setInteger("id", wine_id).list();
					
					if(wines.isEmpty()) {
						response.sendRedirect(name+"?op=list");
					} else {
						session.delete(wines.get(0));
					}
				}
				
				Modwinewines wine = new Modwinewines();
				
				//Set wine Name
				wine.setName(request.getParameter("wine"));
				

				//Year of Wine
				wine.setYear(Integer.parseInt(request.getParameter("year")));
				
				Query sql;
				//Wine Type
				if(request.getParameter("type") != null) {
					sql = session.createQuery("from Modwinetypes where type_id  =:id");
					List<Modwinetypes> types = (List<Modwinetypes>) sql.setString("id", request.getParameter("type")).list();
	
					if(!types.isEmpty())
						wine.setModwinetypes(types.get(0));
				}	
				//Winery
				if(request.getParameter("winery") != null) {
					sql = session.createQuery("from Modwinewineries where wineryName  =:id");
					List<Modwinewineries> winery = (List<Modwinewineries>) sql.setString("id", request.getParameter("winery")).list();
					
					if(!winery.isEmpty())
						wine.setModwinewineries(winery.get(0));
				}
				
				//Price
				wine.setPrice(Float.parseFloat(request.getParameter("price")));
				
				//Description
				wine.setDescription(request.getParameter("description"));
				
				session.save(wine);
				response.sendRedirect(name+"?op=list");
				
				session.getTransaction().commit();
				session.close();	
			}else {
				response.sendRedirect("administrator?op=login");
			}
		}catch(Exception e){
			PrintWriter x = response.getWriter();
			x.write(e.toString()+":"+e.getLocalizedMessage());
		}
	}
	
	@SuppressWarnings("unchecked")
	public void delete(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException {
		try {
		String name = this.getClass().getSimpleName();
		String type_id = (String) request.getParameter("id");
		if(request.getSession().getAttribute("user")!= null) {
			//Prepare Session
			SessionFactory sessionFactory = new Configuration()
				.configure()
				.buildSessionFactory();
			//Start session
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			
			Query sql = session.createQuery("from Modwinewines where wine_id =:id");
			List<Modwinewines> winerys = (List<Modwinewines>) sql.setInteger("id", Integer.parseInt(type_id)).list();
			session.delete(winerys.get(0));
			
			session.getTransaction().commit();
			session.close();
			response.sendRedirect(name+"?op=list");
			
		} else {
			response.sendRedirect("administrator?op=login");
		}
		}catch(Exception e){
			out.write(e.toString());
		}
	}
}
